# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# (C) 2012 Remek Zajac
#!/usr/bin/python

import os
from lxml import etree
import time as time_module

#local imports
import pyGPX        

class RouteSpecialisedParser:
    def __init__(self, parent):
        self.m_fromlatlon = None
        self.m_tolatlon = None
        self.m_parent = parent
        
    def parse(self, elem):
        if elem.tag == "From":
            self.m_fromlatlon = (float(elem.get("lat")), float(elem.get("lon")))
            print self.m_parent.indentationStr()+"Found From:", str(self.m_fromlatlon)
        elif elem.tag == "To":
            self.m_tolatlon = (float(elem.get("lat")), float(elem.get("lon")))
            print self.m_parent.indentationStr()+"Found To:", str(self.m_tolatlon)         
        else:
            print "unsupported tag encoutered", elem.tag

    def execute(self, reportDstPath, callback):
        self.callback = callback
        self.reportDstPath = reportDstPath
        route = self.m_parent.m_parent.route(self.m_fromlatlon, self.m_tolatlon)
        route.do(self.doneRouting)

    def doneRouting(self, fromRoute):
        self.callback(self)
        gpxWriter = pyGPX.WriteGpx()
        rootFileName = os.path.splitext(self.m_parent.m_filename)[0]
        gpxFileName = self.reportDstPath+'/'+rootFileName+'.gpx'
        reportFileName = self.reportDstPath+'/'+rootFileName+'.txt'        
        gpxWriter.do(fromRoute, gpxFileName)
        print "Route saved to file:", gpxFileName
        f = open(reportFileName, "w")
        fromRoute.mainTimer.report(f)
        f.close()
        print "Report saved to file:", reportFileName
        
        

class ScriptingEngine:
    def __init__(self, parent, scriptFileName):
        self.m_parent = parent
        self.m_scriptFileName = scriptFileName
        (self.m_path, self.m_filename) = os.path.split(scriptFileName)        
        self.routeParser = RouteSpecialisedParser(self)
        self.level = 0

    def indentationStr(self):
        str = ('')
        for _ in range(self.level):
            str += '  '
        return str        

    def do(self, callback):
        reportDstPath = self.m_parent.m_config.scripts.outputfolder

        if self.m_parent.m_config.scripts.unique: #unique folder for this run
            timeStruct = time_module.localtime()
            subfolder = time_module.strftime("%Y-%m-%dT%H%M%S", timeStruct)
            reportDstPath += '/'+subfolder
        if not os.path.exists(reportDstPath):
            os.makedirs(reportDstPath)
            
        parsingContext = etree.iterparse( self.m_scriptFileName, events=("start", "end") )
        try:
            for event, elem in parsingContext :
                if event == "start":
                    print self.indentationStr()+'<'+elem.tag+'>'
                    self.level+=1
                else:
                    self.level-=1                    
                    print self.indentationStr()+'<'+elem.tag+'>'              
                if elem.tag == 'ROUTE':
                    if event == "start":
                        self.currentSpecialisedParser = self.routeParser
                    else:
                        self.currentSpecialisedParser.execute(reportDstPath, callback)
                        self.currentSpecialisedParser = None           
                elif self.currentSpecialisedParser:
                    if event == "start":
                        self.currentSpecialisedParser.parse(elem)            
        except etree.XMLSyntaxError:
            assert(False)#failed to parse config file, this is fatal
        del parsingContext
